<template>
  <div class="dashboard">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>欢迎回来, {{ authStore.user?.username }}!</span>
        </div>
      </template>

      <div v-if="authStore.isStudent">
        <h3>我的待办作业</h3>
        <el-table v-loading="loading" :data="studentAssignments" stripe>
          <el-table-column label="作业标题" prop="title" />
          <el-table-column label="所属班级" prop="className" />
          <el-table-column label="截止日期" prop="deadline">
            <template #default="scope">
              {{ formatTime(scope.row.deadline) }}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.status)"
                >{{ statusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="得分">
            <template #default="scope">{{ scope.row.score ?? '-' }}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 'NOT_STARTED' || scope.row.status === 'IN_PROGRESS'"
                size="small"
                type="primary"
                @click="goToAssignment(scope.row.assignmentId)"
              >
                去做作业
              </el-button>
              <el-text v-else type="info">已完成</el-text>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="authStore.isTeacher">
        <p>您好，教师！您可以通过左侧菜单管理您的班级和查看学情分析。</p>
        <el-button type="primary" @click="router.push('/teacher/classes')">进入班级管理</el-button>
      </div>

      <div v-if="authStore.isAdmin">
        <p>您好，管理员！您可以通过左侧菜单管理系统用户。</p>
        <el-button type="primary" @click="router.push('/admin/users')">进入用户管理</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/authStore'
import { apiClient, handleErrorAndRedirect } from '@/api'

const authStore = useAuthStore()
const router = useRouter()
const studentAssignments = ref<any[]>([])
const loading = ref(false)

const formatTime = (isoString: string) => new Date(isoString).toLocaleString()

const statusMap: Record<
  string,
  { text: string; type: 'info' | 'primary' | 'success' | 'warning' }
> = {
  NOT_STARTED: { text: '未开始', type: 'info' },
  IN_PROGRESS: { text: '进行中', type: 'primary' },
  SUBMITTED: { text: '已提交', type: 'success' },
  GRADED: { text: '已批改', type: 'warning' },
}
const statusText = (status: string) => statusMap[status]?.text || '未知'
const statusTagType = (status: string) => statusMap[status]?.type || 'info'

const fetchStudentAssignments = async () => {
  if (!authStore.isStudent) return
  loading.value = true
  try {
    const response = await apiClient.get('/student/me/assignments')
    studentAssignments.value = response.data
  } catch (error) {
    handleErrorAndRedirect(error, '获取作业列表失败')
  } finally {
    loading.value = false
  }
}

const goToAssignment = (id: number) => {
  router.push(`/assignment/${id}`)
}

onMounted(() => {
  fetchStudentAssignments()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}
</style>
